package net.lanelife.casino.caipiao.entity;

import java.io.IOException;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;

import net.lanelife.casino.caipiao.job.JobInfo;
import net.lanelife.casino.common.entity.support.PersistableEntity;

import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "TB_JOB")
public class Job extends PersistableEntity<Integer> {

	private static final long serialVersionUID = 4776767756055905652L;
	
	public static final ObjectMapper MAPPER = new ObjectMapper();
	
	
	@Enumerated(EnumType.ORDINAL)
	@Column(name = "TYPE", nullable = false)
	private JobType type;
	
	@Column(name="INFO", length = 2000, nullable = false)
	private String info;
	
	@Column(name="CREATED_DATE", nullable = false)
	@Type(type = "net.lanelife.casino.common.entity.usertype.PersistentDateTimeAsMillisLong")
	private DateTime createdDate = DateTime.now();
	
	@Column(name="UUID", length = 36)
	private String uuid;
	
	public static enum JobType {
		RECHARGE,
		WITHDRAW_APPLY, WITHDRAW_ACCEPT, WITHDRAW_REJECT,
		TRANSFER_APPLY, TRANSFER_ACCEPT, TRANSFER_REJECT, TRANSFER_CANCEL
	}
	
	public Job() {}
	
	public Job(JobType type) {
		this.type = type;
	}

	public JobType getType() {
		return type;
	}

	public void setType(JobType type) {
		this.type = type;
	}

	public DateTime getCreatedDate() {
		return createdDate;
	}

	public void setCreatedDate(DateTime createdDate) {
		this.createdDate = createdDate;
	}

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public String getUuid() {
		return uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
	
	
	public void writeInfo(JobInfo info) throws JsonProcessingException {
		this.setInfo(MAPPER.writeValueAsString(info));
	}
	
	public <T> T readInfo(Class<T> infoType) throws JsonParseException, JsonMappingException, IOException {
		return MAPPER.readValue(getInfo(), infoType);
	}

}
